package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.commen.BaseContext;
import com.itheima.dto.QuestionsAddDto;
import com.itheima.dto.QuestionsListDto;
import com.itheima.mapper.*;
import com.itheima.pojo.*;
import com.itheima.service.QuestionsService;
import com.itheima.vo.PageResultVO;
import com.itheima.vo.questions.QuestionsVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class QuestionsServiceImpl implements QuestionsService {
    @Autowired
    private QuestionsMapper questionsMapper;
    @Autowired
    private CompanysMapper companysMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private QuestionsAuditsMapper questionsAuditsMapper;
    @Autowired
    private QuestionsRecordsMapper questionsRecordsMapper;
    @Autowired
    private QuestionsOptionsMapper questionsOptionsMapper;
    @Autowired
    private SubjectsMapper subjectsMapper;
    @Autowired
    private SubjectsDirectorysMapper subjectsDirectorysMapper;

    @Override
    public PageResultVO<QuestionsVO> findPage(QuestionsListDto questionsListDto) {
        // 1. 根据Dto数据查询对应的Questions信息
        IPage<Questions> p = new Page<>(questionsListDto.getPage(), questionsListDto.getPagesize());
        // 根据公司名称匹配对应的公司ID
        LambdaQueryWrapper<Companys> wrapper1 = new LambdaQueryWrapper<Companys>();
        wrapper1.select(Companys::getId).
                like(questionsListDto.getShortName()!=null,Companys::getShortName, questionsListDto.getShortName());
        List<Object> objects = companysMapper.selectObjs(wrapper1);
        // 多条件查询
        LambdaQueryWrapper<Questions> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(questionsListDto.getSubjectID() != null, Questions::getSubjectID, questionsListDto.getSubjectID()).
                eq(questionsListDto.getDifficulty() != null, Questions::getDifficulty, questionsListDto.getDifficulty()).
                eq(questionsListDto.getQuestionType() != null, Questions::getQuestionType, questionsListDto.getQuestionType()).
                eq(questionsListDto.getTags() != null, Questions::getTags, questionsListDto.getTags()).
                eq(questionsListDto.getProvince() != null, Questions::getProvince, questionsListDto.getProvince()).
                eq(questionsListDto.getCity() != null, Questions::getCity, questionsListDto.getCity()).
                like(questionsListDto.getKeyword() != null, Questions::getQuestion, questionsListDto.getKeyword()).
                like(questionsListDto.getRemarks() != null, Questions::getRemarks, questionsListDto.getRemarks()).
                in(objects != null, Questions::getEnterpriseID, objects).
                eq(questionsListDto.getDirection() != null, Questions::getDirection, questionsListDto.getDirection()).
                eq(questionsListDto.getCreatorID() != null, Questions::getCreatorID, questionsListDto.getCreatorID()).
                eq(questionsListDto.getCatalogID() != null, Questions::getCatalogID, questionsListDto.getCatalogID()).
                eq(Questions::getIsChoice,0);
        // 根据不同条件查询对应的Page项
        IPage<Questions> questionsIPage = questionsMapper.selectPage(p, wrapper);
        // 填充返回值对象数据
        PageResultVO<QuestionsVO> pageResultVO = new PageResultVO<>();
        pageResultVO.setCounts((int) questionsIPage.getTotal());
        pageResultVO.setPagesize((int) questionsIPage.getSize());
        pageResultVO.setPages((int) questionsIPage.getPages());
        pageResultVO.setPage((int) questionsIPage.getCurrent());
        List<Questions> records = questionsIPage.getRecords();
        //将records转化为QuestionsVO,并补充缺少的数据
        String s = JSON.toJSONString(records);
        List<QuestionsVO> questionsVOS = JSON.parseArray(s, QuestionsVO.class);
        for (QuestionsVO questionsVO : questionsVOS) {
            //根据creatorID查找对应的creator名字
            User user = userMapper.selectById(questionsVO.getCreatorID());
            questionsVO.setCreator(user.getUsername());
            //查询subjectName
            Subjects subjects = subjectsMapper.selectById(questionsVO.getSubjectID());
            questionsVO.setSubject(subjects.getSubjectName());
            //查询目录名
            SubjectsDirectorys subjectsDirectorys = subjectsDirectorysMapper.selectById(questionsVO.getCatalogID());
            questionsVO.setCatalog(subjectsDirectorys.getDirectoryName());
        }
        pageResultVO.setItems(questionsVOS);
        return pageResultVO;
    }

    @Override
    public String delete(Integer id) {
        LambdaQueryWrapper<QuestionsAudits> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuestionsAudits::getQuestionsID, id);
        questionsAuditsMapper.delete(wrapper);
        LambdaQueryWrapper<QuestionsRecords> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(QuestionsRecords::getQuestionsID, id);
        questionsRecordsMapper.delete(wrapper1);
        LambdaQueryWrapper<QuestionsOptions> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(QuestionsOptions::getQuestionsID, id);
        questionsOptionsMapper.delete(wrapper2);
        return null;
    }

    @Override
    public Integer add(QuestionsAddDto questionsAddDto) {
        List<QuestionsOptions> options = questionsAddDto.getOptions();
        questionsAddDto.setNumber(UUID.randomUUID().toString().replaceAll("-",""));
        questionsAddDto.setIsChoice(0);
        questionsAddDto.setPublishState(0);
        questionsAddDto.setPublishDate(new Date());
        questionsAddDto.setChkState(0);
        questionsAddDto.setCreatorID(Math.toIntExact(BaseContext.threadLocal.get()));
        questionsAddDto.setAddDate(new Date());
        questionsMapper.insert(questionsAddDto);
        Integer id = questionsAddDto.getId();
        //遍历添加QuestionsOptions中的QuestionsID
        for (QuestionsOptions option : options) {
            option.setQuestionsID(id);
            questionsOptionsMapper.insert(option);
        }
        return id;
    }

    @Override
    public QuestionsVO findById(Integer id) {
        Questions questions = questionsMapper.selectById(id);
        QuestionsVO questionsVO = new QuestionsVO();
        //将原生pojo复制给VO对象
        BeanUtils.copyProperties(questions,questionsVO);
        LambdaQueryWrapper<QuestionsOptions> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QuestionsOptions::getQuestionsID,id);
        List<QuestionsOptions> questionsOptions = questionsOptionsMapper.selectList(wrapper);
        questionsVO.setOptions(questionsOptions);
        //查询subjectName
        Subjects subjects = subjectsMapper.selectById(questionsVO.getSubjectID());
        questionsVO.setSubject(subjects.getSubjectName());
        //查询目录名
        SubjectsDirectorys subjectsDirectorys = subjectsDirectorysMapper.selectById(questionsVO.getCatalogID());
        questionsVO.setCatalog(subjectsDirectorys.getDirectoryName());
        return questionsVO;
    }

    @Override
    public String edit(QuestionsAddDto questionsAddDto) {
        questionsMapper.updateById(questionsAddDto);
        List<QuestionsOptions> options = questionsAddDto.getOptions();
        for (QuestionsOptions option : options) {
            questionsOptionsMapper.updateById(option);
        }
        return "{'success':true}";
    }

    @Override
    public String setChoice(Integer id, Integer publishState) {
        Questions questions = new Questions();
        questions.setId(id);
        questions.setPublishState(publishState);
        questionsMapper.updateById(questions);
        return "{'success':true}";
    }

    @Override
    public PageResultVO<QuestionsVO> findChoicePage(QuestionsListDto questionsListDto) {
        // 1. 根据Dto数据查询对应的Questions信息
        IPage<Questions> p = new Page<>(questionsListDto.getPage(), questionsListDto.getPagesize());
        // 根据公司名称匹配对应的公司ID
        LambdaQueryWrapper<Companys> wrapper1 = new LambdaQueryWrapper<Companys>();
        wrapper1.select(Companys::getId).
                like(questionsListDto.getShortName()!=null,Companys::getShortName, questionsListDto.getShortName());
        List<Object> objects = companysMapper.selectObjs(wrapper1);
        // 多条件查询
        LambdaQueryWrapper<Questions> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(questionsListDto.getSubjectID() != null, Questions::getSubjectID, questionsListDto.getSubjectID()).
                eq(questionsListDto.getDifficulty() != null, Questions::getDifficulty, questionsListDto.getDifficulty()).
                eq(questionsListDto.getQuestionType() != null, Questions::getQuestionType, questionsListDto.getQuestionType()).
                eq(questionsListDto.getTags() != null, Questions::getTags, questionsListDto.getTags()).
                eq(questionsListDto.getProvince() != null, Questions::getProvince, questionsListDto.getProvince()).
                eq(questionsListDto.getCity() != null, Questions::getCity, questionsListDto.getCity()).
                like(questionsListDto.getKeyword() != null, Questions::getQuestion, questionsListDto.getKeyword()).
                like(questionsListDto.getRemarks() != null, Questions::getRemarks, questionsListDto.getRemarks()).
                in(objects != null, Questions::getEnterpriseID, objects).
                eq(questionsListDto.getDirection() != null, Questions::getDirection, questionsListDto.getDirection()).
                eq(questionsListDto.getCreatorID() != null, Questions::getCreatorID, questionsListDto.getCreatorID()).
                eq(questionsListDto.getCatalogID() != null, Questions::getCatalogID, questionsListDto.getCatalogID()).
                eq(Questions::getIsChoice,1).
                eq(questionsListDto.getChkState()!=null, Questions::getChkState,questionsListDto.getChkState());
        // 根据不同条件查询对应的Page项
        IPage<Questions> questionsIPage = questionsMapper.selectPage(p, wrapper);
        // 填充返回值对象数据
        PageResultVO<QuestionsVO> pageResultVO = new PageResultVO<QuestionsVO>();
        pageResultVO.setCounts((int) questionsIPage.getTotal());
        pageResultVO.setPagesize((int) questionsIPage.getSize());
        pageResultVO.setPages((int) questionsIPage.getPages());
        pageResultVO.setPage((int) questionsIPage.getCurrent());
        List<Questions> records = questionsIPage.getRecords();
        //将records转化为QuestionsVO,并补充缺少的数据
        String s = JSON.toJSONString(records);
        List<QuestionsVO> questionsVOS = JSON.parseArray(s, QuestionsVO.class);
        for (QuestionsVO questionsVO : questionsVOS) {
            //根据creatorID查找对应的creator名字
            User user = userMapper.selectById(questionsVO.getCreatorID());
            questionsVO.setCreator(user.getUsername());
            questionsVO.setChkUser(user.getUsername());
            //查询subjectName
            Subjects subjects = subjectsMapper.selectById(questionsVO.getSubjectID());
            questionsVO.setSubject(subjects.getSubjectName());
            //查询目录名
            SubjectsDirectorys subjectsDirectorys = subjectsDirectorysMapper.selectById(questionsVO.getCatalogID());
            questionsVO.setCatalog(subjectsDirectorys.getDirectoryName());
        }
        pageResultVO.setItems(questionsVOS);
        return pageResultVO;
    }

    @Override
    public PageResultVO<QuestionsVO> findRandomsByKeyword(Integer page, Integer pagesize, String keyword) {
        IPage<Questions> p = new Page<>(page, pagesize);
        LambdaQueryWrapper<Questions> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(keyword != null, Questions::getNumber, keyword);
        IPage<Questions> questionsIPage = questionsMapper.selectPage(p, wrapper);
        // 填充返回值对象数据
        PageResultVO<QuestionsVO> pageResultVO = new PageResultVO<QuestionsVO>();
        pageResultVO.setCounts((int) questionsIPage.getTotal());
        pageResultVO.setPagesize((int) questionsIPage.getSize());
        pageResultVO.setPages((int) questionsIPage.getPages());
        pageResultVO.setPage((int) questionsIPage.getCurrent());
        List<Questions> records = questionsIPage.getRecords();
        //将records转化为QuestionsVO,并补充缺少的数据
        String s = JSON.toJSONString(records);
        List<QuestionsVO> questionsVOS = JSON.parseArray(s, QuestionsVO.class);
        for (QuestionsVO questionsVO : questionsVOS) {
            //根据creatorID查找对应的creator名字
            User user = userMapper.selectById(questionsVO.getCreatorID());
            questionsVO.setAddTime(questionsVO.getAddDate()+"");
            questionsVO.setUserName(user.getUsername());
            //组集合数据空缺
            questionsVO.setQuestionIDs(null);
            questionsVO.setProgressOfAnswer(null);
            questionsVO.setAccuracyRate(null);
            questionsVO.setTotalSeconds(null);
            questionsVO.setQuestionType(questionsVO.getQuestionType());
            //查询subjectName
            Subjects subjects = subjectsMapper.selectById(questionsVO.getSubjectID());
            questionsVO.setSubject(subjects.getSubjectName());
            //查询目录名
            SubjectsDirectorys subjectsDirectorys = subjectsDirectorysMapper.selectById(questionsVO.getCatalogID());
            questionsVO.setCatalog(subjectsDirectorys.getDirectoryName());
        }
        pageResultVO.setItems(questionsVOS);
        return pageResultVO;
    }

    @Override
    public String setChoice1(Integer id, Integer choiceState) {
        Questions questions = new Questions();
        questions.setId(id);
        questions.setIsChoice(choiceState);
        questionsMapper.updateById(questions);
        return "{'success':true}";
    }

    @Override
    public String setCheck(Integer id, Questions questions) {
        questionsMapper.updateById(questions);
        return "";
    }
}
